package com.ruoyi.framework.controller;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.ocr_api20210707.Client;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardRequest;
import com.aliyun.ocr_api20210707.models.RecognizeIdcardResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import com.google.gson.Gson;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.framework.config.ServerConfig;
import com.ruoyi.function.domain.bo.UserBo;
import com.ruoyi.function.service.FileUploadService;
import com.ruoyi.function.service.IUserService;
import com.ruoyi.function.utility.AliyunConfig;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;

@RestController
@RequestMapping("/api/auth")
public class TechnicianAuthController {

    private static final Logger log = LoggerFactory.getLogger(TechnicianAuthController.class);

    @Autowired
    private IUserService userService;

    @Autowired
    private FileUploadService fileUploadService;
  // 注入技师服务

    @Autowired
    private AliyunConfig aliyunConfig;
    @Autowired
    private ServerConfig serverConfig;// 注入配置类


    private Client createClient() throws Exception {
        Config config = new Config()
            .setAccessKeyId(aliyunConfig.getAccessKeyId())
            .setAccessKeySecret(aliyunConfig.getAccessKeySecret());
        config.endpoint = "ocr-api.cn-hangzhou.aliyuncs.com";
        return new Client(config);
    }

    /**
     * 上传身份证并识别
     */
    @Anonymous
    @PostMapping("/upload/{side}")
    public AjaxResult uploadIdCard(@PathVariable("side") String side,
                                 @RequestParam("file") MultipartFile file) {
        try {
            // 先打印配置信息，添加null检查
            log.info("阿里云配置信息 - AccessKeyId: {}, Region: {}",
                aliyunConfig.getAccessKeyId() != null ?
                    (aliyunConfig.getAccessKeyId().substring(0, Math.min(4, aliyunConfig.getAccessKeyId().length())) + "****") : "null",
                aliyunConfig.getRegionId());

            // 1. 检查文件
            if (file == null || file.isEmpty()) {
                return AjaxResult.error("请选择文件");
            }

            // 2. 检查阿里云配置
            if (StringUtils.isEmpty(aliyunConfig.getAccessKeyId()) ||
                StringUtils.isEmpty(aliyunConfig.getAccessKeySecret())) {
                return AjaxResult.error("阿里云OCR配置未设置");
            }

            // 3. 检查文件类型
            String contentType = file.getContentType();
            if (contentType == null || !contentType.startsWith("image/")) {
                return AjaxResult.error("请上传图片文件");
            }

            // 4. 读取文件内容
            byte[] imageBytes = file.getBytes();
            log.info("读取文件成功，大小: {} bytes", imageBytes.length);

            // 5. 创建OCR客户端
            Client client = createClient();

            // 6. 创建识别请求
            RecognizeIdcardRequest request = new RecognizeIdcardRequest();
            request.setBody(new ByteArrayInputStream(imageBytes));

            // 7. 发送请求
            RuntimeOptions runtime = new RuntimeOptions();
            RecognizeIdcardResponse response = client.recognizeIdcardWithOptions(request, runtime);

            log.info("OCR识别响应: {}", new Gson().toJson(response));

            if (response == null || response.getBody() == null) {
                return AjaxResult.error("OCR识别失败：响应为空");
            }

            // 解析响应结果
            JSONObject responseJson = JSONObject.parseObject(new Gson().toJson(response));
            if (responseJson == null || responseJson.getJSONObject("body") == null) {
                return AjaxResult.error("OCR识别失败：响应为空");
            }

            // 解析body中的data字符串
            String dataStr = responseJson.getJSONObject("body").getString("data");
            JSONObject fullData = JSONObject.parseObject(dataStr);
            
            if (fullData == null) {
                return AjaxResult.error("OCR识别失败：数据解析失败");
            }
            
            log.info("解析后的数据: {}", fullData.toJSONString());
            
            // 根据side参数获取正面或背面数据
            JSONObject cardData = null;
            if ("front".equals(side)) {
                // 正面
                if (fullData.getJSONObject("data") != null && 
                    fullData.getJSONObject("data").getJSONObject("face") != null) {
                    cardData = fullData.getJSONObject("data").getJSONObject("face").getJSONObject("data");
                }
            } else {
                // 背面
                if (fullData.getJSONObject("data") != null && 
                    fullData.getJSONObject("data").getJSONObject("back") != null) {
                    cardData = fullData.getJSONObject("data").getJSONObject("back").getJSONObject("data");
                }
            }
            
            if (cardData == null) {
                // 如果无法解析OCR数据，返回错误
                return AjaxResult.error("OCR识别失败：无法识别身份证信息，请确保上传的是清晰的身份证照片");
            }

            // 保存文件
//            String filePath = fileUploadService.uploadFile(file, "idcard");
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            log.info("文件保存路径: {}", filePath);
            String fileName = FileUploadUtils.upload(filePath, file);
             filePath = serverConfig.getUrl() + fileName;
            log.info("文件保存成功，路径: {}", filePath);

            // 返回结果
            return AjaxResult.success()
                .put("filePath", filePath)
                .put("ocrData", cardData);

        } catch (Exception e) {
            log.error("OCR识别异常", e);
            return AjaxResult.error("OCR识别异常：" + e.getMessage());
        }
    }

    /**
     * 提交身份证认证
     */
    @PostMapping("/idcard/submit")
    public AjaxResult submitIdCardAuth(@Validated @RequestBody UserBo user) {

        // 提交认证
        boolean result = userService.submitIdCardAuth(user);
        
        return result ? AjaxResult.success() : AjaxResult.error("提交失败");
    }


}